package com.sgb.kjwl.pop;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.PopwindowMainPublishBinding;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.fragment.home.MainPublishMenuFragment;
import com.swgk.core.dialog.BaseBottomDialog;
import com.swgk.core.recyclerview.adapter.FragPagerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author : 作者
 * @Time : On 2020/11/25 11:08
 * @Page: On com.sgb.kjwl.view.widget.share
 * @Description : MainPublishDialog
 */
public class MainPublishDialog extends DialogFragment {
    private RecyclerView rl_rv_menu;
    private TextView tv_cancel;
    private FragPagerAdapter menuAdapter;
    private DialogClickCallBack dialogClickCallBack;
    private ArrayList<Fragment> menuFragments;
    private int page;
    public static final int COLUMN_COUNT = 5;
    public static final int ROW_COUNT = 2;
    private MainActivity mMainActivity;
    private ViewPager viewpager;
    private ImageView[] memuTip;
    private LinearLayout llViewpager;
    private LinearLayout dotMenuLayout;
    private Boolean Flag=false;


    private PopwindowMainPublishBinding binding;
    private List<MenuEntity> mMenuData;

    public MainPublishDialog(Context context, List<MenuEntity> data, BaseBottomDialog.DialogCallBack dialogCallBack) {
        mMainActivity = (MainActivity) context;
        mMenuData = data;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.popwindow_main_publish, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    protected void initView(View view) {
//        rl_rv_menu = holder.getDialog().findViewById(R.id.rv_menu);
        tv_cancel = view.findViewById(R.id.img_close);
        viewpager = view.findViewById(R.id.viewpager);
        llViewpager = view.findViewById(R.id.ll_viewpager);
        dotMenuLayout = view.findViewById(R.id.dot_menu_layout);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        showMenuView(mMenuData);
    }

    public interface DialogClickCallBack {
        void onItemClick(String ids);
    }

    private void showMenuView(List<MenuEntity> data) {
        if(data==null||data.size() == 0)return;
        if (menuFragments == null)
            menuFragments = new ArrayList<>();
        menuFragments.clear();
        int total = data.size();
        page = total % (COLUMN_COUNT * ROW_COUNT) > 0 ? total / (COLUMN_COUNT * ROW_COUNT) + 1 : total / (COLUMN_COUNT * ROW_COUNT);
        for (int i = 0; i < page; i++) {
            List<MenuEntity> menuEntityList = new ArrayList<>();
            int fir = i * COLUMN_COUNT * ROW_COUNT;
            int last = (i + 1) * COLUMN_COUNT * ROW_COUNT > total ? total : (i + 1) * COLUMN_COUNT * ROW_COUNT;
            menuEntityList.addAll(data.subList(fir, last));
            menuFragments.add(MainPublishMenuFragment.newInstance(menuEntityList, COLUMN_COUNT, ROW_COUNT, i));
            MainPublishMenuFragment big = (MainPublishMenuFragment) menuFragments.get(i);
            big.setOnItemClickCallBack(new MainPublishMenuFragment.OnItemClickCallBack() {
                @Override
                public void onClick(MenuEntity entity, int position) {
                    dialogClickCallBack.onItemClick(entity.getName());
                }
            });
        }
        menuAdapter = new FragPagerAdapter(getChildFragmentManager(), menuFragments);
        viewpager.setAdapter(menuAdapter);
        viewpager.setOffscreenPageLimit(page);
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setImageBackgroundMenu(position % page);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        initDotsMenu();
        llViewpager.setVisibility(View.VISIBLE);
    }

    public MainPublishDialog setDialogClickCallBack(DialogClickCallBack dialogClickCallBack) {
        this.dialogClickCallBack = dialogClickCallBack;
        return this;
    }

    private void setImageBackgroundMenu(int selectItems) {
        for (int i = 0; i < memuTip.length; i++) {
            if (i == selectItems) {
                memuTip[i].setSelected(true);
            } else {
                memuTip[i].setSelected(false);
            }
        }
    }

    private void initDotsMenu() {
        if(page>1) {
            dotMenuLayout.setVisibility(View.VISIBLE);
            dotMenuLayout.removeAllViews();
            memuTip = new ImageView[page];
            for (int i = 0; i < page; i++) {
                ImageView imageView = new ImageView(this.mMainActivity);
                imageView.setBackgroundResource(R.drawable.select_banner_dot);
                memuTip[i] = imageView;
                if (i == 0) {
                    memuTip[i].setSelected(true);
                } else {
                    memuTip[i].setSelected(false);
                }
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams((int) mMainActivity.getResources().getDimension(R.dimen.dp6), (int) mMainActivity.getResources().getDimension(R.dimen.dp6)));
                layoutParams.leftMargin = (int) mMainActivity.getResources().getDimension(R.dimen.dp5);
                layoutParams.rightMargin = (int) mMainActivity.getResources().getDimension(R.dimen.dp5);
                dotMenuLayout.addView(imageView, layoutParams);
            }
        }else{
            dotMenuLayout.setVisibility(View.GONE);
        }
    }



    public void setvisibility(int visibility){
        dotMenuLayout.setVisibility(visibility);
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        window.setWindowAnimations(com.swgk.core.R.style.dialogWindowAnim); //设置窗口弹出动画
        window.setBackgroundDrawableResource(com.swgk.core.R.color.transparent); //设置对话框背景为透明
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
    }

//    @Override
//    public void dismiss() {
//        super.dismiss();
//        Flag=false;
//    }

    @Override
    public void show(FragmentManager manager, String tag) {
         if(!Flag) {
             Flag=true;
             if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
                 if (manager.isDestroyed())
                     return;
             }
             try {
                 //在每个add事务前增加一个remove事务，防止连续的add
                 manager.beginTransaction().remove(this).commit();
                 super.show(manager, tag);
             } catch (Exception e) {
                 //同一实例使用不同的tag会异常，这里捕获一下
                 e.printStackTrace();
             }
         }
    }

    public void setmMenuData(List<MenuEntity> data) {
        if (null != data && data.size() != 0){
            this.mMenuData = data;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Flag=false;
    }
}
